package com.art.sunflower.controller;

import com.art.sunflower.exception.NullCooperationException;
import com.art.sunflower.pojo.Cooperation;
import com.art.sunflower.service.CooperationService;
import com.art.sunflower.util.AddFile;
import com.art.sunflower.util.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@CrossOrigin
@RequestMapping(value = "cooperation")
@Api(value = "合作单位")
public class CooperationController {
    @Resource
    CooperationService cooperationService;

    @PostMapping()
    @RequiresRoles(value = {"admin"})
    @ApiOperation("上传一个合作单位")
    public Message insert(@RequestParam("mfile") MultipartFile mfile, int id, String co_name, String co_introduce) {
        AddFile addFile = new AddFile();
        String url = addFile.addFile(mfile, "cooperation");
        Cooperation cooperation = new Cooperation();
        cooperation.setCoName(co_name);
        cooperation.setUrl(url);
        cooperation.setCoIntroduce(co_introduce);
        System.out.println(cooperation.toString());
        int count = cooperationService.insert(cooperation);
        if (count > 0) {
            return Message.createSuc("添加成功");
        }
        return Message.createErr("增加失败");
    }

    @DeleteMapping(value = "/{id}")
    @RequiresRoles(value = {"admin"})
    @ApiOperation("删除一个合作单位")
    public Message delete(@PathVariable int id) {
        int count = cooperationService.delete(id);
        if (count > 0) {
            return Message.createSuc("删除成功");
        }
        return Message.createErr("删除失败");
    }


    @GetMapping()
    @ApiOperation("分页获取合作单位列表")
    public Message listAllWork(Integer pageSize, Integer pageNo) {
        try {
            return Message.createSuc(cooperationService.listAll(pageSize, pageNo));
        } catch (NullCooperationException e) {
            e.printStackTrace();
            return Message.createErr("合作单位不存在");
        }

    }

    @GetMapping(value = "/{id}")
    @ApiOperation("获取一个合作单位信息")
    public Message select(@PathVariable int id) {
        if (cooperationService.selectOne(id) == null) {
            return Message.createErr("编号不存在，查找失败");
        } else {
            return Message.createSuc(cooperationService.selectOne(id));
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation("获取合作单位大纲列表")
    public Message listIdName() {
        try {
            return Message.createSuc(cooperationService.listIdName());
        } catch (NullCooperationException e) {
            e.printStackTrace();
            return Message.createErr("合作单位不存在");
        }

    }
}
